package com.icinfo.cloud.provider.punish.common.seal.utils;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业和个人信息的接口
 *
 * @author yunchao.peng
 * @create 2023-07-28 17:06
 */
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "info")
public class ChongQingInfoUtil {
    private static final TimedCache<String, String> timedCache = CacheUtil.newTimedCache(4);

    //    private static final String URL = "http://23.212.180.252:8070";
    private static final String URL = "http://23.99.94.212:3022";

    private static final String ENT_FIRST = "/services/RES_SGSJDH/qyjbxx/%s";
    private static final String PERSON_FIRST = "/services/RES_SGAJPP/hjrkxx/%s";

    /**
     * token的获取
     *
     * @return
     */
    public static String getAuthToken() {
        return "56fa2e51f49cbf6b31ce358f2a684e65_f509358bc11fdb5b4e4f9df5a933ade1";
//        String token = timedCache.get("info_token");
//        if (StringUtils.isNotBlank(token)) {
//            log.info("获取查询法人和个人的token接口缓存token========:" + token);
//            return token;
//        }
//        String url = URL + "/rest/exchangeToken";
//        HttpRequest post = HttpUtil.createPost(url);
//        HashMap<String, Object> param = new HashMap<>();
//        param.put("mIp", "23.99.94.218");
//        param.put("mApp", "乡村执法");
//        post.form(param);
//        String body = post.execute().body();
//        log.info("获取查询法人和个人的token接口详情,{}", body);
//        JSONObject response = JSONObject.parseObject(body);
//        if (HttpStatus.HTTP_OK == response.getInteger("status")) {
//            String newToken = response.getString("token");
//            timedCache.put("info_token", newToken, 3600);
//            log.info("获取查询法人和个人的获取token========:" + newToken);
//            return newToken;
//        }
//        throw new BusinessException("获取查询法人和个人的token接口异常");
    }


    /**
     * 拼接token连接
     *
     * @param url
     * @return
     */
    private static String getTotkenUrl(String url) {
        String token = getAuthToken();
        url = String.format(url, token);
        return url;
    }


    /**
     * 拼接参数返回执行结果
     *
     * @param searchInfoParam
     * @param firstUrl
     * @param lastTitle
     * @return
     */
    public static String execte(SearchInfoParam searchInfoParam, String firstUrl, String lastTitle) {
        // http://23.99.94.212:3022/services/RES_SGSJDH/qyjbxx/{{token}}/getDataJsonWithoutTitle?pageNo=1&pageSize=2&search=[{"ENTNAME.eq":"沙坪坝区柊柠百货经营部"},{"UNISCID.eq":"92500106MA60WW202T"}]
        String url = URL + firstUrl + "/" + lastTitle;
        url = getTotkenUrl(url);
        if (null == searchInfoParam.getPageNo() && null == searchInfoParam.getPageSize()) {
            url += "?search=%s";
            url = String.format(url, URLEncoder.encode(SearchInfoParam.toParam(searchInfoParam.getSearch())));
        } else {
            url += "?pageNo=%s&pageSize=%s&search=%s";
            url = String.format(url, searchInfoParam.getPageNo(), searchInfoParam.getPageSize(), URLEncoder.encode(SearchInfoParam.toParam(searchInfoParam.getSearch())));
        }
        log.info("请求全路径:{}", url);
        String body = HttpRequest.post(url).timeout(3000 * 1000).execute().body();
        log.info("请求路径-结果:{},{}", url, body);
        if (StringUtils.isBlank(body)) {
            throw new HttpException("重庆查询接口请求失败");
        }
        JSONObject data = JSONObject.parseObject(body);
        return data.getJSONObject(lastTitle + "Response").getString("return");
    }

    /**
     * 根据统一信用代码和企业名称查询数据
     *
     * @param name
     * @param unicode
     * @return
     */
    public static List<EntEqInfo.DataBean.ResultBean> getEqEntInfo(String name, String unicode) {
        if (StringUtils.isAllEmpty(name, unicode)) {
            throw new IllegalArgumentException();
        }
        String lastTitle = "getDataJsonWithoutTitle";
        ArrayList<SearchInfoKeyValue> searchInfoKeyValues = new ArrayList<>();
        if (StringUtils.isNotEmpty(name)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("ENTNAME", "eq", name));
        }
        if (StringUtils.isNotEmpty(unicode)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("UNISCID", "eq", unicode));
        }
        SearchInfoParam searchInfoParam = new SearchInfoParam(1, 5, searchInfoKeyValues);
        String execte = execte(searchInfoParam, ENT_FIRST, lastTitle);
        EntEqInfo data = JSONObject.parseObject(execte, EntEqInfo.class);
        if (data.getCode() != Constant.INTEGER_1) {
            throw new BusinessException("准确查询企业信息失败");
        }
        return data.getData().getResult();
    }

    /**
     * 根据统一信用代码和企业名称查询数据
     *
     * @param name
     * @return
     */
    public static java.util.List<EntLikeInfo.DataBean.ResultBean> getLikeEntInfo(String name, String unicode, Integer pageSize) {
        if (StringUtils.isAllEmpty(name)) {
            throw new IllegalArgumentException();
        }
        String lastTitle = "getDataJsonWithoutTitle";
        ArrayList<SearchInfoKeyValue> searchInfoKeyValues = new ArrayList<>();
        if (StringUtils.isNotEmpty(name)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("ENTNAME", "like", name + "%"));
        }
        if (StringUtils.isNotEmpty(unicode)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("UNISCID", "eq", unicode));
        }
        SearchInfoParam searchInfoParam = new SearchInfoParam(1, pageSize == null ? 5 : pageSize, searchInfoKeyValues);
        String execte = execte(searchInfoParam, ENT_FIRST, lastTitle);
        EntLikeInfo data = JSONObject.parseObject(execte, EntLikeInfo.class);
        return data.getData().getResult();
    }

    /**
     * 查询企业是否存在
     *
     * @param name
     * @param unicode
     * @return
     */
    public static Boolean getEntIsHas(String name, String unicode) {
        if (StringUtils.isAllEmpty(name, unicode)) {
            throw new IllegalArgumentException();
        }
        String lastTitle = "getIsHasData";
        ArrayList<SearchInfoKeyValue> searchInfoKeyValues = new ArrayList<>();
        if (StringUtils.isNotEmpty(name)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("ENTNAME", "eq", name));
        }
        if (StringUtils.isNotEmpty(unicode)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("UNISCID", "eq", unicode));
        }
        SearchInfoParam searchInfoParam = new SearchInfoParam(searchInfoKeyValues);
        String execte = execte(searchInfoParam, ENT_FIRST, lastTitle);
        return "true".equals(execte);
    }

    /**
     * 根据身份证号码查询数据
     *
     * @param sfzhm
     * @return
     */
    public static List<PersonInfo.DataBean.ResultBean> getPersonInfo(String sfzhm) {
        if (StringUtils.isBlank(sfzhm)) {
            throw new IllegalArgumentException();
        }
        String lastTitle = "getDataJsonWithoutTitle";
        ArrayList<SearchInfoKeyValue> searchInfoKeyValues = new ArrayList<>();
        if (StringUtils.isNotEmpty(sfzhm)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("SFZHM", "eq", sfzhm));
        }
        SearchInfoParam searchInfoParam = new SearchInfoParam(1, 5, searchInfoKeyValues);
        String execte = execte(searchInfoParam, PERSON_FIRST, lastTitle);
        PersonInfo personInfo = JSONObject.parseObject(execte, PersonInfo.class);
        if (personInfo.getCode() != Constant.INTEGER_1) {
            throw new BusinessException("根据身份证号码查询个人信息失败");
        }
        log.info(personInfo.getData().getResult().toString());
        return personInfo.getData().getResult();
    }

    /**
     * 根据身份证号码查询数据
     *
     * @param name  姓名
     * @param sfzhm
     * @return
     */
    public static Boolean getIsHasPersonInfo(String name, String sfzhm) {
        if (StringUtils.isAllEmpty(name, sfzhm)) {
            throw new IllegalArgumentException();
        }
        String lastTitle = "getIsHasData";
        ArrayList<SearchInfoKeyValue> searchInfoKeyValues = new ArrayList<>();
        if (StringUtils.isNotEmpty(name)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("XM", "eq", name));
        }
        if (StringUtils.isNotEmpty(sfzhm)) {
            searchInfoKeyValues.add(new SearchInfoKeyValue("SFZHM", "eq", sfzhm));
        }
        SearchInfoParam searchInfoParam = new SearchInfoParam(1, 5, searchInfoKeyValues);
        String execte = execte(searchInfoParam, PERSON_FIRST, lastTitle);
        return "true".equals(execte);
    }

    public static void main(String[] args) {
//        getPersonInfo("510212198212081328");
//        System.out.println(getEntIsHas(null, "915000003316147440"));
        System.out.println(getIsHasPersonInfo(null, "510212198212081328"));
//        getEqEntInfo(null, "915000003316147440");
//        List<EntLikeInfo.DataBean.ResultBean> data = getLikeEntInfo("沙坪坝区",2);
//        System.out.println(JSONObject.toJSONString(data));

    }

}
